package com.diandian.backend.order.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.diandian.backend.order.clients.DianDianStoreClient;
import com.diandian.backend.order.clients.dto.StoreDouyinLifeStoreInfoListParamDTO;
import com.diandian.backend.order.clients.dto.StoreDouyinLifeStoreInfoListRespDTO;
import com.diandian.backend.order.domain.OrderOnlineDouyinLife;
import com.diandian.backend.order.dto.*;
import com.diandian.backend.order.mapper.OrderOnlineDouyinLifeMapper;
import com.diandian.backend.order.param.*;
import com.diandian.backend.order.resp.OrderOnlineDouyinLifeDetailResp;
import com.diandian.backend.order.resp.OrderOnlineDouyinLifeImportResp;
import com.diandian.backend.order.resp.OrderOnlineDouyinLifePageResp;
import com.diandian.base.boot.starter.exception.DefaultException;
import com.diandian.base.boot.starter.response.BaseResult;
import com.diandian.base.boot.starter.response.PageResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class OrderOnlineDouyinLifeService {

    private static final Logger logger = LoggerFactory.getLogger(OrderOnlineDouyinLifeService.class);

    @Autowired
    private OrderOnlineDouyinLifeMapper orderOnlineDouyinLifeMapper;

    @Autowired
    private OrderOnlineDouyinLifeDetailService orderOnlineDouyinLifeDetailService;

    @Autowired
    private DianDianStoreClient dianDianStoreClient;

    private static  int IMPORT_TOTAL_COUNT = 0; // 导入总数量
    private static int IMPORT_SUCCESS_COUNT = 0; // 执行导入数量
    private static int IMPORT_EXECUTE_COUNT = 0; // 执行次数

    public PageResult page(OrderOnlineDouyinLifePageParamDTO requestDTO){

        requestDTO.check();
        int pageSize = requestDTO.getPageSize();
        int pageNum = requestDTO.getPageNum();

        // 查询总数
        int totalCount = orderOnlineDouyinLifeMapper.getCount(requestDTO);

        // 查询数据集合
        List<OrderOnlineDouyinLife> dataList = orderOnlineDouyinLifeMapper.getPage(requestDTO, requestDTO.getPageSize(), (requestDTO.getPageNum() - 1) * requestDTO.getPageSize());

        // 组装数据
        List<OrderOnlineDouyinLifePageResp> respList = new ArrayList<>();
        if(dataList != null && dataList.size() > 0){
            dataList.stream().forEach( x ->{
                OrderOnlineDouyinLifePageResp item = new OrderOnlineDouyinLifePageResp();
                item.setId(x.getId());
                item.setBelong(x.getBelong());
                item.setOnlineOrderNum(x.getOnlineOrderNum());
                item.setOnlineOrderType(x.getOnlineOrderType());
                item.setOnlineOrderTime(x.getOnlineOrderTime());
                item.setOnlineOrderCouponCount(x.getOnlineOrderCouponCount());
                item.setOnlineOrderPrice(x.getOnlineOrderPrice());
                item.setOnlineChannel(x.getOnlineChannel());
                item.setOnlineOrderStoreOfflineCode(x.getOnlineOrderStoreOfflineCode());
                item.setOnlineOrderStoreOnlineCode(x.getOnlineOrderStoreOnlineCode());
                item.setOnlineOrderStoreOnlineName(x.getOnlineOrderStoreOnlineName());
                item.setCreateTime(x.getCreateTime());
                item.setUpdateTime(x.getUpdateTime());
                item.setDel(x.getDel());
                item.setStatus(x.getStatus());
                item.setOpenId(x.getOpenId());
                item.setRoomId(x.getRoomId());
                item.setRoomOfflineStoreCode(x.getRoomOfflineStoreCode());
                item.setRoomOfflineStoreName(x.getRoomOfflineStoreName());
                item.setRoomOnlineStoreCode(x.getRoomOnlineStoreCode());
                item.setRoomOnlineStoreName(x.getRoomOnlineStoreName());
                respList.add(item);
            });
        }

        return new PageResult(pageNum, pageSize, totalCount, respList);
    }

    public OrderOnlineDouyinLifeDetailResp getDetail(OrderOnlineDouyinLifeDetailParamDTO param) {

        OrderOnlineDouyinLife dbData = orderOnlineDouyinLifeMapper.getDetail(param);
        if(dbData == null){
            return null;
        }

        OrderOnlineDouyinLifeDetailResp result = new OrderOnlineDouyinLifeDetailResp();
        result.setId(dbData.getId());
        result.setBelong(dbData.getBelong());
        result.setOnlineOrderNum(dbData.getOnlineOrderNum());
        result.setOnlineOrderType(dbData.getOnlineOrderType());
        result.setOnlineOrderTime(dbData.getOnlineOrderTime());
        result.setOnlineOrderCouponCount(dbData.getOnlineOrderCouponCount());
        result.setOnlineOrderPrice(dbData.getOnlineOrderPrice());
        result.setOnlineChannel(dbData.getOnlineChannel());
        result.setOnlineOrderStoreOfflineCode(dbData.getOnlineOrderStoreOfflineCode());
        result.setOnlineOrderStoreOnlineCode(dbData.getOnlineOrderStoreOnlineCode());
        result.setOnlineOrderStoreOnlineName(dbData.getOnlineOrderStoreOnlineName());
        result.setCreateTime(dbData.getCreateTime());
        result.setUpdateTime(dbData.getUpdateTime());
        result.setDel(dbData.getDel());
        result.setStatus(dbData.getStatus());
        result.setOpenId(dbData.getOpenId());
        result.setRoomId(dbData.getRoomId());
        result.setRoomOfflineStoreCode(dbData.getRoomOfflineStoreCode());
        result.setRoomOfflineStoreName(dbData.getRoomOfflineStoreName());
        result.setRoomOnlineStoreCode(dbData.getRoomOnlineStoreCode());
        result.setRoomOnlineStoreName(dbData.getRoomOnlineStoreName());
        return result;
    }

    /**
     * 更新订单状态
     * @param data
     */
    public void updateStatus(OrderOnlineDouyinLifeUpdateParamParam data){

        String onlineOrderNum = data.getOnlineOrderNum();
        String belong = data.getBelong();
        String status = data.getStatus();

        // 查询订单详情
        OrderOnlineDouyinLife orderDTO = orderOnlineDouyinLifeMapper.queryDetail(belong, onlineOrderNum);
        if(orderDTO == null){
            logger.info("{}下的订单{}不存在，不再执行后续处理。", belong, onlineOrderNum);
            return;
        }

        // 执行更新
        orderOnlineDouyinLifeMapper.updateStatus(belong, onlineOrderNum, status, new Date());
    }

    /**
     * 保存单个
     */
    @Transactional(rollbackFor = Exception.class)
    public void sychOne(OrderOnlineDouyinLifeAddOneParam order){

        String onlineOrderNum = order.getOnlineOrderNum();
        String belong = order.getBelong();

        // 查询订单详情
        OrderOnlineDouyinLife orderDTO = orderOnlineDouyinLifeMapper.queryDetail(belong, onlineOrderNum);
        if(orderDTO != null){
            orderOnlineDouyinLifeMapper.deleteByOrderNumAndBelong(belong, onlineOrderNum);
            orderOnlineDouyinLifeDetailService.deleteByOrderNumAndBelong(belong, onlineOrderNum);
        }

        // 保存线上订单主表数据
        OrderOnlineDouyinLifeAddParamDTO mainDTO = new OrderOnlineDouyinLifeAddParamDTO();
        mainDTO.setBelong(belong);
        mainDTO.setOnlineOrderNum(order.getOnlineOrderNum());
        mainDTO.setOnlineOrderType(order.getOnlineOrderType());
        mainDTO.setOnlineOrderTime(order.getOnlineOrderTime());
        mainDTO.setOnlineOrderCouponCount(order.getOnlineOrderCouponCount());
        mainDTO.setOnlineOrderPrice(order.getOnlineOrderPrice());
        mainDTO.setOnlineChannel(order.getOnlineChannel());
        mainDTO.setOnlineOrderStoreOnlineCode(order.getOnlineOrderStoreOnlineCode());
        mainDTO.setOnlineOrderStoreOfflineCode(order.getOnlineOrderStoreOfflineCode());
        mainDTO.setOnlineOrderStoreOnlineName(order.getOnlineOrderStoreOnlineName());
        mainDTO.setStatus(order.getStatus());
        mainDTO.setCreateTime(order.getOnlineOrderTime());
        mainDTO.setDel(0);
        mainDTO.setOpenId(order.getOpenId());
        mainDTO.setRoomId(order.getRoomId());
        mainDTO.setRoomOfflineStoreCode(order.getRoomOfflineStoreCode());
        mainDTO.setRoomOfflineStoreName(order.getRoomOfflineStoreName());
        mainDTO.setRoomOnlineStoreCode(order.getRoomOnlineStoreCode());
        mainDTO.setRoomOnlineStoreName(order.getRoomOnlineStoreName());
        orderOnlineDouyinLifeMapper.add(mainDTO);

        // 保存从表数据
        List<OrderOnlineDouyinLifeAddParamDataCertificate> certificates = order.getCertificates();
        if(certificates != null && certificates.size() > 0){
            List<OrderOnlineDouyinLifeDetailAddParamDTO> detailList = new ArrayList<>();
            for (int j = 0; j < certificates.size(); j++) {
                OrderOnlineDouyinLifeDetailAddParamDTO detailDTO = new OrderOnlineDouyinLifeDetailAddParamDTO();
                detailDTO.setBelong(belong);
                detailDTO.setOnlineOrderNum(order.getOnlineOrderNum());
                detailDTO.setOnlineOrderCouponId(certificates.get(j).getOnlineOrderCouponId());
                detailDTO.setOnlineOrderCouponName(certificates.get(j).getOnlineOrderCouponName());
                detailDTO.setCreateTime(order.getOnlineOrderTime());
                detailList.add(detailDTO);
            }
            orderOnlineDouyinLifeDetailService.batchAdd(detailList);
        }
    }

    /**
     * 同步方式的保存
     */
    public void sych(OrderOnlineDouyinLifeAddParam param){

        String belong = param.getBelong();
        Boolean replaceFlag = param.getReplaceFlag();

        // 清空历史数据
        if(replaceFlag != null && replaceFlag){
            logger.info("执行历史数据清理...");
            // 清除主表数据
            orderOnlineDouyinLifeMapper.deleteByTime(belong, param.getStartTime(), param.getEndTime());
            // 清除从表数据
            orderOnlineDouyinLifeDetailService.deleteByTime(belong, param.getStartTime(), param.getEndTime());
            logger.info("历史数据清理完成。");
        }

        // 保存新数据
        saveOrderData(belong, param.getOrderList());
    }

    /**
     * 补充线上订单消息
     * 注：有则跳过，无则新增
     */
    public void supplement(OrderOnlineDouyinLifeAddSupplementParam data){

        // 数据检查
        data.check();

        // 获取参数
        Date time = data.getTime();
        String belong = data.getBelong();

        // 获取当前传入数据的单号
//        List<String> onlineOrderNumList = data.getOrderList().stream().map(order -> order.getOnlineOrderNum()).collect(Collectors.toList());

        // 查询当天补充日期当天的所有订单号
        Date startTime = getDayBeginTime(time);
        Date endTime = getDayEndTime(time);
        List<String> existsOnlineOrderNumList = orderOnlineDouyinLifeMapper.getExistsOnlineOrderNum(belong, startTime, endTime);
        logger.info("当前存在{}日期{}的订单记录数：{}", belong, new SimpleDateFormat("yyyy-MM-dd").format(time), existsOnlineOrderNumList == null ? 0 : existsOnlineOrderNumList.size());

        // 当前没有数据，全部保存
        List<OrderOnlineDouyinLifeAddSupplementParamData> targetSaveList = new ArrayList<>();
        if(existsOnlineOrderNumList == null || existsOnlineOrderNumList.size() == 0){
            targetSaveList = data.getOrderList();
        } else {
            // 过滤出需要保存的数据
            for (int i = 0; i <  data.getOrderList().size(); i++) {
                String onlineOrderNum = data.getOrderList().get(i).getOnlineOrderNum();
                if(!existsOnlineOrderNumList.contains(onlineOrderNum)){
                    targetSaveList.add(data.getOrderList().get(i));
                }
            }
        }

        if(targetSaveList == null || targetSaveList.size() == 0){
            logger.info("当前没有需要补充的数据，跳过后续处理。");
            return;
        }

        // 组装数据
        List<OrderOnlineDouyinLifeAddParamDTO> mainList = new ArrayList<>();
        List<OrderOnlineDouyinLifeDetailAddParamDTO> detailList = new ArrayList<>();
        for (int i = 0; i < targetSaveList.size(); i++) {

            OrderOnlineDouyinLifeAddSupplementParamData order = targetSaveList.get(i);

            // 线上订单主表数据
            OrderOnlineDouyinLifeAddParamDTO mainDTO = new OrderOnlineDouyinLifeAddParamDTO();
            mainDTO.setBelong(belong);
            mainDTO.setOnlineOrderNum(order.getOnlineOrderNum());
            mainDTO.setOnlineOrderType(order.getOnlineOrderType());
            mainDTO.setOnlineOrderTime(order.getOnlineOrderTime());
            mainDTO.setOnlineOrderCouponCount(order.getOnlineOrderCouponCount());
            mainDTO.setOnlineOrderPrice(order.getOnlineOrderPrice());
            mainDTO.setOnlineChannel(order.getOnlineChannel());
            mainDTO.setOnlineOrderStoreOnlineCode(order.getOnlineOrderStoreOnlineCode());
            mainDTO.setOnlineOrderStoreOfflineCode(order.getOnlineOrderStoreOfflineCode());
            mainDTO.setOnlineOrderStoreOnlineName(order.getOnlineOrderStoreOnlineName());
            mainDTO.setStatus(order.getStatus());
            mainDTO.setCreateTime(order.getOnlineOrderTime());
            mainList.add(mainDTO);

            // 组装线上订单从表数据
            List<OrderOnlineDouyinLifeAddParamDataCertificate> certificates = order.getCertificates();
            if(certificates != null && certificates.size() > 0){
                for (int j = 0; j < certificates.size(); j++) {
                    OrderOnlineDouyinLifeDetailAddParamDTO detailDTO = new OrderOnlineDouyinLifeDetailAddParamDTO();
                    detailDTO.setBelong(belong);
                    detailDTO.setOnlineOrderNum(order.getOnlineOrderNum());
                    detailDTO.setOnlineOrderCouponId(certificates.get(j).getOnlineOrderCouponId());
                    detailDTO.setOnlineOrderCouponName(certificates.get(j).getOnlineOrderCouponName());
                    detailDTO.setCreateTime(order.getOnlineOrderTime());
                    detailList.add(detailDTO);
                }
            } else {
                logger.info("第{}个元素的券信息为空，数据：{}", (i + 1), JSON.toJSONString(order));
            }
        }

        // 保存线上订单主表数据
        logger.info("当前需要补充主表记录数：{}", mainList.size());
        batchAdd(mainList);

        // 保存线上订单从表数据
        logger.info("当前需要补充从表记录数：{}", detailList.size());
        orderOnlineDouyinLifeDetailService.batchAdd(detailList);

        logger.info("执行抖音本地生活订单数据补充逻辑完成。");
    }

    /**
     * 获取某天的开始时间
     * @return
     */
    private Date getDayBeginTime(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    /**
     * 获取某天的结束时间
     */
    private Date getDayEndTime(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    /**
     * 组装并保存订单数据
     * @param belong
     * @param orderList
     */
    private void saveOrderData(String belong, List<OrderOnlineDouyinLifeAddParamData> orderList){

        logger.info("执行订单数据组装、保存逻辑...");

        if(orderList == null || orderList.size() == 0){
            logger.info("订单数据为空，不再执行后续处理。");
            return;
        }

        // 组装数据
        List<OrderOnlineDouyinLifeAddParamDTO> mainList = new ArrayList<>();
        List<OrderOnlineDouyinLifeDetailAddParamDTO> detailList = new ArrayList<>();
        for (int i = 0; i < orderList.size(); i++) {

            OrderOnlineDouyinLifeAddParamData order = orderList.get(i);

            // 线上订单主表数据
            OrderOnlineDouyinLifeAddParamDTO mainDTO = new OrderOnlineDouyinLifeAddParamDTO();
            mainDTO.setBelong(belong);
            mainDTO.setOnlineOrderNum(order.getOnlineOrderNum());
            mainDTO.setOnlineOrderType(order.getOnlineOrderType());
            mainDTO.setOnlineOrderTime(order.getOnlineOrderTime());
            mainDTO.setOnlineOrderCouponCount(order.getOnlineOrderCouponCount());
            mainDTO.setOnlineOrderPrice(order.getOnlineOrderPrice());
            mainDTO.setOnlineChannel(order.getOnlineChannel());
            mainDTO.setOnlineOrderStoreOnlineCode(order.getOnlineOrderStoreOnlineCode());
            mainDTO.setOnlineOrderStoreOfflineCode(order.getOnlineOrderStoreOfflineCode());
            mainDTO.setOnlineOrderStoreOnlineName(order.getOnlineOrderStoreOnlineName());
            mainDTO.setStatus(order.getStatus());
            mainDTO.setCreateTime(order.getOnlineOrderTime());
            mainDTO.setOpenId(order.getOpenId());
            mainDTO.setRoomId(order.getRoomId());
            mainDTO.setRoomOfflineStoreCode(order.getRoomOfflineStoreCode());
            mainDTO.setRoomOfflineStoreName(order.getRoomOfflineStoreName());
            mainDTO.setRoomOnlineStoreCode(order.getRoomOnlineStoreCode());
            mainDTO.setRoomOnlineStoreName(order.getRoomOnlineStoreName());
            mainList.add(mainDTO);

            // 组装线上订单从表数据
            // 订单类型：90
//            if("90".equals(order.getOrder_type())){
//                List<QueryOnlineOrderPageResponseDataOrderCertificate> certificates = order.getCertificate();
//                if(certificates != null && certificates.size() > 0){
//                    for (int j = 0; j < certificates.size(); j++) {
//                        OrderDouyinLifeOnlineDetailAddParamDTO detailDTO = new OrderDouyinLifeOnlineDetailAddParamDTO();
//                        detailDTO.setOnlineOrderNum(order.getOrder_id());
//                        detailDTO.setOnlineOrderCouponId(certificates.get(j).getCertificate_id());
//                        detailDTO.setOnlineOrderCouponName(order.getSku_name());
//                        detailList.add(detailDTO);
//                    }
//                } else {
//                    logger.info("第{}个元素的券信息为空，数据：{}", (i + 1), JSON.toJSONString(order));
//                }
//            }
//            // 订单类型：21
//            if("21".equals(order.getOrder_type())){
//                List<QueryOnlineOrderPageResponseDataOrderCertificate> products = order.getProducts();
//                if(products != null && products.size() > 0){
//                    for (int j = 0; j < products.size(); j++) {
//                        OrderDouyinLifeOnlineDetailAddParamDTO detailDTO = new OrderDouyinLifeOnlineDetailAddParamDTO();
//                        detailDTO.setOnlineOrderNum(order.getOrder_id());
//                        detailDTO.setOnlineOrderCouponId(certificates.get(j).getCertificate_id());
//                        detailDTO.setOnlineOrderCouponName(order.getSku_name());
//                        detailList.add(detailDTO);
//                    }
//                } else {
//                    logger.info("第{}个元素的券信息为空，数据：{}", (i + 1), JSON.toJSONString(order));
//                }
//            }

            List<OrderOnlineDouyinLifeAddParamDataCertificate> certificates = order.getCertificates();
            if(certificates != null && certificates.size() > 0){
                for (int j = 0; j < certificates.size(); j++) {
                    OrderOnlineDouyinLifeDetailAddParamDTO detailDTO = new OrderOnlineDouyinLifeDetailAddParamDTO();
                    detailDTO.setBelong(belong);
                    detailDTO.setOnlineOrderNum(order.getOnlineOrderNum());
                    detailDTO.setOnlineOrderCouponId(certificates.get(j).getOnlineOrderCouponId());
                    detailDTO.setOnlineOrderCouponName(certificates.get(j).getOnlineOrderCouponName());
                    detailDTO.setCreateTime(order.getOnlineOrderTime());
                    detailList.add(detailDTO);
                }
            } else {
                logger.info("第{}个元素的券信息为空，数据：{}", (i + 1), JSON.toJSONString(order));
            }
        }

        // 保存线上订单主表数据
        batchAdd(mainList);

        // 保存线上订单从表数据
        orderOnlineDouyinLifeDetailService.batchAdd(detailList);

        logger.info("订单数据组装、保存完成。");
    }

    /**
     * 批量保存订单数据
     * @param dataList
     */
    private void batchAdd(List<OrderOnlineDouyinLifeAddParamDTO> dataList) {
        if(dataList == null || dataList.isEmpty()) {
            return;
        }

        dataList.forEach( x -> {
            x.setDel(0);
        });

        List<List<OrderOnlineDouyinLifeAddParamDTO>> partitionList = Lists.partition(dataList,100);
        for (int i = 0; i < partitionList.size(); i++) {
            orderOnlineDouyinLifeMapper.batchAdd(partitionList.get(i));
        }
    }

    /**
     * 导入补充数据（抖音号、订单编号）
     * @param multipartFile
     * @param belong
     * @return
     */
    public OrderOnlineDouyinLifeImportResp importOrderData(MultipartFile multipartFile, String belong){

        IMPORT_TOTAL_COUNT = 0;
        IMPORT_SUCCESS_COUNT = 0;
        IMPORT_EXECUTE_COUNT = 0;

        // 1. 接收文件
        File file = multipartFileToFile(multipartFile);

        // 2. 获取所有抖音号和门店信息的关联数据
        Map<String, StoreDouyinLifeStoreInfoListRespDTO> relationMap = getRelationMap(belong);

        // 3. 读取数据并分批处理
        readAndHandler(file, belong, relationMap);

        // 返回结果
        return new OrderOnlineDouyinLifeImportResp(IMPORT_TOTAL_COUNT, IMPORT_SUCCESS_COUNT, IMPORT_TOTAL_COUNT - IMPORT_SUCCESS_COUNT);
    }

    /**
     * MultipartFile转为File
     * @param multipartFile
     * @return
     */
    private File multipartFileToFile(MultipartFile multipartFile){
        File file = new File(multipartFile. getOriginalFilename());
        try {
            InputStream inputStream = multipartFile.getInputStream();
            OutputStream outputStream = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream. read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if(file == null){
            throw new DefaultException("文件不合法");
        }
        return file;
    }

    /**
     * 获取抖音号和门店的管理数据
     * @param belong
     * @return
     */
    private Map<String, StoreDouyinLifeStoreInfoListRespDTO> getRelationMap(String belong){
        Map<String, StoreDouyinLifeStoreInfoListRespDTO> result = new HashMap<>();
        StoreDouyinLifeStoreInfoListParamDTO storeDouyinLifeStoreInfoListParamDTO = new StoreDouyinLifeStoreInfoListParamDTO();
        storeDouyinLifeStoreInfoListParamDTO.setBelongEql(belong);
        BaseResult baseResult = dianDianStoreClient.getStoreList(storeDouyinLifeStoreInfoListParamDTO);
        if(baseResult != null && baseResult.getCode() == 0 && baseResult.getData() != null){
            List<StoreDouyinLifeStoreInfoListRespDTO> storeInfoList = JSONArray.parseArray(JSON.toJSONString(baseResult.getData()), StoreDouyinLifeStoreInfoListRespDTO.class);
            if(storeInfoList != null && storeInfoList.size() > 0){
                for (int i = 0; i < storeInfoList.size(); i++) {
                    String douyinNum = storeInfoList.get(i).getRoomId();
                    if(douyinNum != null && !"".equals(douyinNum)){
                        String[] douyinNumArray = douyinNum.split(",");
                        for (int j = 0; j < douyinNumArray.length; j++) {
                            result.put(douyinNumArray[j], storeInfoList.get(i));
                        }
                    }
                }
            }
        }
        if(result.size() == 0){
            throw new DefaultException("未配置抖音号，请配置抖音号后重试");
        }
        return result;
    }


    /**
     * 读取并分批处理数据
     * @param file
     * @return
     */
    private Object readAndHandler(File file, String belong, Map<String, StoreDouyinLifeStoreInfoListRespDTO> relationMap){


        EasyExcel.read(file, OrderOnlineDouyinLifeImportDataDTO.class, new ReadListener<OrderOnlineDouyinLifeImportDataDTO>() {

            // 单次缓存的数据量
            public static final int BATCH_COUNT = 100;
            // 临时存储
            private List<OrderOnlineDouyinLifeImportDataDTO> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

            @Override
            public void invoke(OrderOnlineDouyinLifeImportDataDTO data, AnalysisContext context) {

                IMPORT_TOTAL_COUNT++;

                // 过滤不合法数据
                if(data.getDouyinNum() == null || "".equals(data.getDouyinNum().trim()) || data.getOnlineOrderNum() == null || "".equals(data.getOnlineOrderNum().trim())){
                    return;
                }
                cachedDataList.add(data);

                // 达到批次，执行一次数据处理
                if (cachedDataList.size() >= BATCH_COUNT) {
                    execute();
                    // 存储完成清理 list
                    cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
                }
            }

            /**
             * 所有数据解析完成了，都会来调用
             * @param context
             */
            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                // 这里也要保存数据，确保最后遗留的数据也存储到数据库
                if(cachedDataList != null && cachedDataList.size() > 0){
                    execute();
                }
                logger.info("所有数据解析完成！");
            }

            /**
             * 批次数据处理
             */
            private void execute() {

                IMPORT_EXECUTE_COUNT++;
                logger.info("正在执行第{}次数据导入...", IMPORT_EXECUTE_COUNT);

                if(cachedDataList != null && cachedDataList.size() > 0){
                    List<OrderOnlineDouyinLifeBatchUpdateRoomInfoDTO> dataList = new ArrayList<>();

                    for (int i = 0; i < cachedDataList.size(); i++) {
                        String douyinNum = cachedDataList.get(i).getDouyinNum();
                        String onlineOrderNum = cachedDataList.get(i).getOnlineOrderNum();
                        StoreDouyinLifeStoreInfoListRespDTO store = relationMap.get(douyinNum);
                        if(store != null){
                            String onlineStoreCode = store.getOnlineCode();
                            String onlineStoreName = store.getOnlineName();
                            String offlineStoreCode = store.getOfflineCode();
                            dataList.add(new OrderOnlineDouyinLifeBatchUpdateRoomInfoDTO(onlineOrderNum, new Date(), offlineStoreCode, null, onlineStoreCode, onlineStoreName));
                            IMPORT_SUCCESS_COUNT++;
                        }
                    }
                    if(dataList.size() > 0){
                        orderOnlineDouyinLifeMapper.batchUpdateRoomInfo(belong, dataList);
                    }
                }
            }
        }).sheet().doRead();

        return null;
    }

}
